package client;

import common.CMessage;
import common.CMessage.CClientInfo;

public class CClientData {
	private int i_clientid; public int GetClientId(){ return i_clientid;} 
	private CClientInfo arr_clientinfo[];
    private final Object lock = new Object();
	protected int 	i_totplayer;
	private String s_ChatMsg;  
    public CClientData(int totplayer){
		i_clientid = -1;
    	i_totplayer = totplayer;
		arr_clientinfo = new CClientInfo[i_totplayer];
		for(int i=0; i<i_totplayer; i++)
			arr_clientinfo[i] = new CClientInfo();
		s_ChatMsg = new String("");
    }
    //Use this to Signal client data has been updated (i.e. new data received from server has been processed)
    public void signal() {
        synchronized (lock) {
            lock.notifyAll();
        }
    }
    public void SetClientId(int i){
    	i_clientid = i;
    	signal();
    }
    
    //Use this to Wait for client data update (i.e. waiting for server to send more data)
    public void await() throws InterruptedException {
        synchronized (lock) {
            lock.wait();
        }
    }
    public String GetChatMsg(){ 
    	String ret = new String(s_ChatMsg); 
    	s_ChatMsg = ""; 
    	return ret;
    }
	
    public void UpdateClientInfo(CMessage msg){
		for(int i = 0; i<i_totplayer; i++){
			arr_clientinfo[i].i_clientid = ((CClientInfo)msg.arr_data[i]).i_clientid;
			arr_clientinfo[i].s_clientip = ((CClientInfo)msg.arr_data[i]).s_clientip;
			arr_clientinfo[i].s_clientname = ((CClientInfo)msg.arr_data[i]).s_clientname;
		}
		signal();
		msg.printclientinfo();
	}
	
	public void UpdateChatMsg(CMessage msg){
		String sMsg = (String)msg.arr_data[0];
		s_ChatMsg = (sMsg + "\n");
		signal();
		return;
	}
	
	public String GetConnectedClientName(int id){
		if(id<0 || id >=i_totplayer)
			return null;
		return arr_clientinfo[id].s_clientname;
	}

}
